import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


class AjaxUser{
    public String username;
    public String password;
}

class Judge {
    public String flg;
}

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    //判断登录状态
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用当前方法判断登录状态

        //1.获取当前的会话
        HttpSession session = req.getSession(false);
        if(session == null) {
            //无会话,当前是未登录状态
            resp.setStatus(403);
            return;
        }
        //这里的user对象需要判断是否存在
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);
    }

    //登录界面
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDao userDao = new UserDao();
        Judge judge = new Judge();

//        //从form表单发送的请求中获取到body内容
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");

        //从ajax发送post请求 body中带有 username 和 password 属性
        ObjectMapper objectMapper = new ObjectMapper();
        //获取body中的属性
        AjaxUser ajaxUser = objectMapper.readValue(req.getInputStream(),AjaxUser.class);
        String username = ajaxUser.username;
        String password = ajaxUser.password;

        //判断账号密码是否为空
        if(username == null || password == null || username == "" || password == "" ) {
            judge.flg = "false";
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(objectMapper.writeValueAsString(judge));
            return;
        }

        User user = userDao.selectByName(username);
        //判断账号密码是否正确
        if(user == null || !user.getPassword().equals(password)) {
            judge.flg = "false";
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(objectMapper.writeValueAsString(judge));
            return;
        }

        //到这一步,说明账号密码均正确
        resp.setContentType("application/json;charset=utf8");
        //创建会话
        HttpSession session = req.getSession(true);
        //在会话中存储user对象
        session.setAttribute("user",user);
        //重定向到博客列表页
        resp.sendRedirect("blog_list.html");

    }
}
